package com.example.lenovo.manager;

import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.avos.avoscloud.AVCloudQueryResult;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.CloudQueryCallback;
import com.avos.avoscloud.FindCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;


public class ProductDelete extends Fragment {

    private ListView listView;
    private List<Map<String,Object>> list = new ArrayList<>();
    private List<AVObject> mData = new ArrayList<>();



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        System.out.println("00");
        View view = inflater.inflate(R.layout.fragment_product_delete, container, false);

        System.out.println("01");
        listView = (ListView) view.findViewById(R.id.ProductDelete);

        System.out.println("02");
        AVOSCloud.initialize(getActivity(), "Po6OudEc9QxRgv1qcussxBxi-gzGzoHsz", "EFNsW7y5aXtKMkpU50xyhHNk");
        final AVQuery<AVObject> query = new AVQuery<>("ProductInfo");
        query.findInBackground(new FindCallback<AVObject>() {


            @Override
            public void done(final List<AVObject> listr, AVException e) {
                final List<AVObject> priorityEqualsZeroTodos = listr;
                mData = listr;
                for(int i = 0;i<priorityEqualsZeroTodos.size();i++){
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("productname", priorityEqualsZeroTodos.get(i).getString("productname"));
                    System.out.println("Name：" + priorityEqualsZeroTodos.get(i).getString("productname"));
                    map.put("productprice", priorityEqualsZeroTodos.get(i).getString("productprice"));
                    list.add(map);
                    System.out.println(priorityEqualsZeroTodos.get(i).toJSONObject().toString());
                    System.out.println(map.toString());
                }
                String[] from = {"productname","productprice"};
                int[] to = {R.id.NameTable,R.id.PriceTable};
                MyAdapter simpleAdapter = new MyAdapter(getActivity(),list,R.layout.listview_item,from,to);
                listView.setAdapter(simpleAdapter);
                listView.setOnItemClickListener(
                        new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Toast.makeText(getActivity(),"This is "+position+" 行！",Toast.LENGTH_LONG).show();
                            }
                        }
                );
                setListViewHeightBasedOnChildren(listView);
            }
        });

        return view;
    }


    public void showInfo(final int position, final List<AVObject> IdList){

        ImageView img=new ImageView(getActivity());
        /*img.setImageResource(R.drawable.b);*/
        new AlertDialog.Builder(getActivity())
                .setTitle("确认删除吗？")
                .setMessage("产品名"+IdList.get(position).getString("productname")+"\n产品描述："+IdList.get(position).getString("productdeclear")+"\n价格:"+IdList.get(position).getString("productprice"))
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AVQuery.doCloudQueryInBackground("delete from ProductInfo where objectId='" + IdList.get(position).getObjectId() + "'", new CloudQueryCallback<AVCloudQueryResult>() {
                            @Override
                            public void done(AVCloudQueryResult avCloudQueryResult, AVException e) {
                                ProductDelete productDelete = new ProductDelete();
                                FragmentManager fragmentManager = getFragmentManager();
                                FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
                                beginTransaction.replace(R.id.FrameOut, productDelete);
                                beginTransaction.commit();
                            }
                        });
                    }
                })
                .show();
    }


    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }


    /**
     * 重写的数据适配器
     */
    class MyAdapter extends SimpleAdapter {

        LayoutInflater inflater;

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final Holder holder;
            final int num=position;
            if(convertView!=null){
                holder=(Holder) convertView.getTag();
            }else {
                holder=new Holder();
                convertView=inflater.inflate(R.layout.listview_item, null);
                holder.Name = (TextView) convertView.findViewById(R.id.NameTable);
                holder.Price = (TextView) convertView.findViewById(R.id.PriceTable);
                holder.DeleteButton = (Button) convertView.findViewById(R.id.DeleteTable);
                convertView.setTag(holder);
            }


            for(int i = 0;i<mData.size();i++){
                holder.Name.setText(mData.get(i).getString("productname"));
                holder.Price.setText(mData.get(i).getString("productprice"));

            }

            View.OnClickListener listener=new View.OnClickListener(){
                @Override
                public void onClick(View v)
                {
                    showInfo(position,mData);
                }
            };
            holder.DeleteButton.setOnClickListener(listener);





            return super.getView(position, convertView, parent);
        }

        public MyAdapter(Context context, List<? extends Map<String, ?>> data,
                          int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
//          this.context=context;
            inflater=LayoutInflater.from(context);
            // TODO Auto-generated constructor stub
        }
    }

    class Holder{
        public TextView Name,Price;
        public Button DeleteButton;
    }




}
